import { defineStore } from 'pinia'
import { ref } from 'vue'
import { concatPlayList } from '@/utils/util'

export const usePlayerStore = defineStore(
  'player',
  () => {
    // 登录状态
    const isLogin = ref(false)
    // 显示/隐藏登录弹窗
    const loginDialogVisible = ref(false)
    // 当前播放状态
    const isPlayer = ref(false)
    // 播放列表
    const playList = ref([])
    // 用户信息
    const userInfo = ref(null)
    // 当前播放歌曲下标
    const playIndex = ref(0)
    // 添加及播放成功后，播放列表按钮提示的文字
    const isShowPlayListTips = ref(false)

    // 当前歌曲在播放列表的索引
    const findIndex = (list, playList) => playList.value.findIndex((i) => i.id === list.id)

    // 播放歌曲列表里全部歌曲（清空当前播放列表）
    const playAll = ({ list }) => {
      setPlayList(concatPlayLists(list))
      setPlayStatus(true)
      setPlayIndex(0)
    }

    // 获取播放列表
    const setPlayList = (val = null) => {
      playList.value = val
      window.localStorage.setItem('playList', JSON.stringify(val))
    }

    // 设置播放状态
    const setPlayStatus = (val = false) => (isPlayer.value = val)

    // 设置当前播放歌曲下标
    const setPlayIndex = (val = 0) => {
      playIndex.value = val
      window.localStorage.setItem('playIndex', val)
    }

    // 播放当前选择的音乐
    const selectPlay = ({ list }) => {
      const playList = concatPlayLists(list, playList.value)
      setPlayList(playList)
      setPlayStatus(true)
      setPlayIndex(findIndex(list[0], playList))
    }

    // 设置播放列表按钮提示的文字
    const setPlayListTips = (val = false) => (isShowPlayListTips.value = val)

    // 合并歌曲到播放列表查重
    const concatPlayLists = (list, playList = []) =>
      concatPlayList(
        list.filter((item) => !item.license && !item.vip),
        playList
      )

    // 添加歌曲到当前播放列表
    const addList = ({ list }) => {
      const playList = concatPlayLists(list, playList.values)
      setPlayList(playList)
      setPlayListTips(true)
    }
    return {
      isLogin,
      loginDialogVisible,
      isPlayer,
      playList,
      userInfo,
      playIndex,
      isShowPlayListTips,
      findIndex,
      playAll,
      setPlayList,
      setPlayStatus,
      setPlayIndex,
      selectPlay,
      setPlayListTips,
      concatPlayLists,
      addList
    }
  },
  { persist: true }
)
